package com.imooc.business.core.executor.query;

import com.imooc.business.context.DataContext;
import com.imooc.business.core.executor.query.base.ResultService;
import com.imooc.module.collect.request.ParamsRequest;
import com.imooc.module.exception.DataCenterException;
import com.imooc.module.query.enums.OrganType;
import com.imooc.module.query.request.QueryRequest;
import com.imooc.module.query.request.SupportType;
import com.imooc.user.provider.model.GroupType;
import com.imooc.user.provider.model.UserCenterGroupVo;
import com.imooc.user.provider.service.UserCenterGroupService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @Author Tim
 * @Description: 查询处理器
 * @Version 1.0
 */
@Component
public class DefaultQueryProcess implements QueryProcess{

    @DubboReference(check = false)
    protected UserCenterGroupService groupService;

    private final List<ResultService> resultServices;

    public DefaultQueryProcess(List<ResultService> resultServices) {
        this.resultServices = resultServices;
    }

    @Override
    public void query(DataContext context) {
        ParamsRequest paramsRequest = context.getRequest();
        QueryRequest queryRequest = paramsRequest.getQueryRequest();
        String requestGroupId = queryRequest.getRequestGroupId();
        UserCenterGroupVo group = Optional.ofNullable(groupService.getGroupByGroupId(requestGroupId)).
                orElseThrow(()->new DataCenterException("当前群组id不存在"));

        queryRequest.setGroup(group);

        GroupType groupType = GroupType.parse(group.getGroupType());
        SupportType.SupportTypeBuilder supportTypeBuilder = SupportType.builder();
        supportTypeBuilder.organType(OrganType.USER);
        supportTypeBuilder.tableType(queryRequest.getTableType());

        switch (groupType){
            case GRADE,ORDINARY -> supportTypeBuilder.organType(OrganType.GROUP);
            case EDUCATION -> supportTypeBuilder.organType(OrganType.SCHOOL);
        }
        SupportType supportType = supportTypeBuilder.build();
        resultServices.parallelStream().filter(resultService ->
                resultService.supportType(supportType)).forEach(resultService -> resultService.buildResult(context));
    }
}
